const KEY = 'goods';

function getJsonObject(argument) {
    //直接返回一个对象
    return JSON.parse(localStorage.getItem(KEY) || '[]');
}


export function setItem(obj) {


    //将数据放到一个数组中
    var arr = getJsonObject();
    arr.push(obj);
    // 把数据 存储在本地
    localStorage.setItem(KEY, JSON.stringify(arr));
}



// [{"count":1,"goodsid":"90"},{"count":2,"goodsid":"90"},{"count":2,"goodsid":"89"},{"count":1,"goodsid":"90"},{"count":2,"goodsid":"90"},{"count":2,"goodsid":"89"}]
export function getItemCount() {
    var list = getJsonObject();
    let sum = 0;
    list.forEach(item => {
        sum += item.count;
    })

    console.log(sum)
    return sum;
}


/**
 * 把当前的商品的数据放购物车拿到所的商品的id号，通过这些组合成的id号可以实现去发送ajax的数据
 * @return {[type]} [description]
 */
export function getIdString() {
    var list = [];
    var obj = getShopCar();
    for (let key in obj) {
        list.push(key);
    }
    //以逗号进行分隔数据 
    return list.join(',');
}



/**
 * 这是获得当前所的分类的本地数据
 * @return {[type]} [description]
 */
export function getShopCar() {
    let list = getJsonObject();
    let obj = {};

    list.forEach(item => {
        if (obj[item.goodsid]) {
            obj[item.goodsid] += item.count;
        } else {
            obj[item.goodsid] = item.count;
        }

    })
    return obj;
}

// 更新数据
// [{"count":1,"goodsid":"90"},{"count":2,"goodsid":"90"},{"count":2,"goodsid":"89"},{"count":1,"goodsid":"90"},{"count":2,"goodsid":"90"},{"count":2,"goodsid":"89"}]
// export function updatashopcar(count) {
//     let currentcount = getShopCar();
//     obj['']
// }
// 
export function substrictItem(goodsid) {
    var list = getJsonObject();
    for (var i = list.length - 1; i >= 0; i--) {
        var tmpobj = list[i];
        if (tmpobj.goodsid == goodsid) {
            if (tmpobj.count == 1) {
                list.splice(i, 1);

            } else {
                list[i].count = list[i].count - 1;
            }
            // 注意如果这个break放在外面，那么数据是没办法删除的
           break;
        }
         
    }

    localStorage.setItem(KEY,JSON.stringify(list))
}

export function removeGoods(id) {
  var arr = [];
 var list =  getJsonObject();
 list.forEach(item=>{
    if(item.goodsid != id){
       arr.push(item);
    }
 })
 // 最后再把数据写出来
 localStorage.setItem(KEY,JSON.stringify(arr))
}
